<template>
  <div class="page-user-login">
    <van-nav-bar
      left-arrow
      @click-left="$router.back()"
      title="登录"
    ></van-nav-bar>
    <!-- 登陆表单 -->
    <van-cell-group>
      <van-field
        v-model="userForm.mobile"
        label="手机号"
        placeholder="请输入手机号"
        @blur="checkMobile"
        :error-message="errorMsg.mobile"
      />
      <van-field
        v-model="userForm.code"
        label="验证码"
        @blur="checkCode"
        :error-message="errorMsg.code"
        placeholder="请输入验证码"
      >
        <template #button>
          <van-button size="small" type="primary">发送验证码</van-button>
        </template>
      </van-field>
    </van-cell-group>
    <div class="btn-box">
      <van-button @click="login" round block type="info">提交</van-button>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'user-chat',
  data () {
    return {
      // 表单数据
      userForm: {
        mobile: '13911111111',
        code: '246810'
      },
      // 验证失败显示的提示
      errorMsg: {
        mobile: '',
        code: ''
      }
    }
  },
  methods: {
    // 校验手机号
    checkMobile () {
      const value = this.userForm.mobile
      if (!value) {
        this.errorMsg.mobile = '  请输入手机号'
      } else if (!/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(value)) {
        this.errorMsg.mobile = '手机号格式不对'
      } else {
        this.errorMsg.mobile = ''
      }
    },
    // 校验验证码
    checkCode () {
      const value = this.userForm.code
      if (!value) {
        this.errorMsg.code = '请输入验证码'
      } else if (!/^\d{6}$/.test(value)) {
        this.errorMsg.code = '验证码6位数字'
      } else {
        this.errorMsg.code = ''
      }
    },
    ...mapMutations(['setToken']),
    // 登陆时 整体校验
    async login () {
      console.log(1111)
      this.checkMobile()
      this.checkCode()
      if (!this.errorMsg.mobile || !this.errorMsg.code) {
        try {
          const { data } = await login(this.userForm)
          this.setToken(data)
          this.$router.push(this.$route.query.redirectUrl || '/user')
          this.$toast.success('登录成功 !')
        } catch (error) {
          this.$toast.fail('手机几号或验证码错误 !')
        }
      }
    }
  }
}
</script>

<style scoped lang='less'></style>
